﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using JKF.DataModule.IDAL;
using JKF.Entities.Model;
using JKF.Substructure;

namespace JKF.DataModule.SqlServerDAL
{
    /// <summary>
    /// 数据访问类dalSMS_SEND_LOG。
    /// </summary>
    public partial class dalSMS_SEND_LOG : IdalSMS_SEND_LOG
    {
        /// <summary>
        /// 获得一个批次待发送短信
        /// </summary>
        /// <returns></returns>
        public static IList<SMS_SEND_LOGinfo> GetSms2Send()
        {
            var db = DB.HR;
            var command = db.GetStoredProcCommand("proc_sms_send_log_get2send");
            var rslt = db.ExecuteDataSet(command);
            if (rslt != null && rslt.Tables.Count > 0)
            {
                var w = (from a in rslt.Tables[0].AsEnumerable()
                         select new SMS_SEND_LOGinfo()
                             {
                                 ID = a.Field<Guid>("ID"),
                                 CONTENT = a.Field<string>("CONTENT"),
                                 MOBILE = a.Field<string>("MOBILE"),
                                 SHOP_CODE = a.Field<string>("SHOP_CODE"),
                                 CONSUME_NUM = a.Field<int>("consume_num")
                             }).ToList();
                return w;
            }
            return new List<SMS_SEND_LOGinfo>();
        }

        /// <summary>
        /// 短信发送完成处理相关状态
        /// </summary>
        /// <param name="smsSendLogId"></param>
        /// <param name="status"></param>
        /// <param name="consumeNum"></param>
        /// <param name="reasonFailed"></param>
        public static bool SendSmsCallBack(Guid smsSendLogId, string status, int consumeNum, string reasonFailed)
        {
            /*
            proc_sms_send_log_sendcallback
	        @ID uniqueidentifier,
	        @STATUS CHAR(1),
	        @CONSUME_NUM INT,
	        @REASON_FAILURE VARCHAR(100)
             */
            var db = DB.HR;
            var rslt = 0;
            var command = db.GetStoredProcCommand("proc_sms_send_log_sendcallback");
            db.AddInParameter(command, "@ID", DbType.Guid, smsSendLogId);
            db.AddInParameter(command, "@STATUS", DbType.String, status);
            db.AddInParameter(command, "@CONSUME_NUM", DbType.Int32, consumeNum);
            db.AddInParameter(command, "@REASON_FAILURE", DbType.String, reasonFailed);
            db.AddOutParameter(command, "@RSLT", DbType.Int32, rslt);
            db.ExecuteNonQuery(command);

            return (rslt == 1);
        }

        /// <summary>
        /// 添加短信
        /// </summary>
        /// <returns></returns>
        public static bool SmsSendLogAdd(SMS_SEND_LOGinfo loginfo)
        {
            //proc_sms_addsms
            var db = DB.HR;
            var rslt = 0;
            var command = DB.HR.GetStoredProcCommand("proc_sms_addsms");
            db.AddInParameter(command, "@ID", DbType.String, loginfo.ID.ToString());
            db.AddInParameter(command, "@MOBILE", DbType.String, loginfo.MOBILE);
            db.AddInParameter(command, "@CONSUME_NUM", DbType.String, loginfo.CONSUME_NUM);
            db.AddInParameter(command, "@IP", DbType.String, loginfo.IP);
            db.AddInParameter(command, "@SHOP_CODE", DbType.String, loginfo.SHOP_CODE);
            db.AddInParameter(command, "@content", DbType.String, loginfo.CONTENT);
            db.AddInParameter(command, "@USER_CREATE", DbType.String, loginfo.USER_CREATE.ToString());
            db.AddInParameter(command, "@CUSTOMER_KEY", DbType.String, loginfo.CUSTOMER_KEY == Guid.Empty ? "" : loginfo.CUSTOMER_KEY.ToString());
            db.AddOutParameter(command, "@RSLT", DbType.Int32, rslt);
            db.ExecuteNonQuery(command);

            return (rslt == 1);
        }

        /// <summary>
        /// 返回是否有短信需要发送
        /// </summary>
        /// <returns></returns>
        public static bool HasSms2Send()
        {
            var db = DB.HR;
            var commdand = db.GetSqlStringCommand("SELECT TOP 1 * FROM SMS_SEND_LOG where status='0' and (status='3' and Retry_times<11)");
            var rslt = db.ExecuteScalar(commdand);
            return (rslt != null);
        }

        /// <summary>
        /// 获得发送记录
        /// </summary>
        /// <param name="sendTimeStart"></param>
        /// <param name="sendTimeEnd"></param>
        /// <param name="shopCode"></param>
        /// <param name="taskType"></param>
        /// <param name="status"></param>
        /// <param name="field"></param>
        /// <param name="fieldValue"></param>
        /// <param name="currentUser"></param>
        /// <param name="pageCurrent"></param>
        /// <param name="pageSize"></param>
        /// <param name="pageCount"></param>
        /// <param name="rowCount"></param>
        /// <returns></returns>
        public static DataTable GetSmsSendedPaging(DateTime? sendTimeStart, DateTime? sendTimeEnd, string shopCode, string taskType,
            string status, string field, string fieldValue, string currentUser, int pageCurrent, int pageSize, ref int pageCount, ref int rowCount)
        {
            var sqlBuilder = new StringBuilder();
            sqlBuilder.AppendFormat(" SHOP_CODE IN (SELECT SHOP_CODE FROM SYS_USER_SHOP WHERE USER_KEY='{0}')", currentUser);
            if (!string.IsNullOrEmpty(shopCode)) sqlBuilder.AppendFormat(" AND SHOP_CODE in('{0}')", string.Join("','", shopCode.Split(',')));
            if (sendTimeStart.HasValue) sqlBuilder.AppendFormat(" AND DATE_SEND>='{0}'", sendTimeStart.Value.ToShortDateLineFormat());
            if (sendTimeEnd.HasValue) sqlBuilder.AppendFormat(" AND DATE_SEND<='{0}'", sendTimeEnd.Value.ToShortDateLineFormat() + " 23:59:59");
            if (!string.IsNullOrEmpty(taskType)) sqlBuilder.AppendFormat(" AND JUST_TIME='{0}'", taskType);
            if (!string.IsNullOrEmpty(status)) sqlBuilder.AppendFormat(" AND status='{0}'", status);
            if ((field.Equals("card_no", StringComparison.CurrentCultureIgnoreCase)
                || field.Equals("customer_name", StringComparison.CurrentCultureIgnoreCase)
                || field.Equals("mobile", StringComparison.CurrentCultureIgnoreCase)
                )
                && !string.IsNullOrEmpty(field) && !string.IsNullOrEmpty(fieldValue)
            )
                sqlBuilder.AppendFormat(" AND {0}='{1}'", field, fieldValue);

            return DataPage.GetPageInfo("VL_SMS_SEND_LOG_VIEW", "ID", pageCurrent, pageSize, "*", "DATE_CREATE", sqlBuilder.ToString(), ref pageCount, ref rowCount).Tables[0];

        }

        /// <summary>
        /// 获取指定用户的发送记录
        /// </summary>
        /// <param name="customerKey"></param>
        /// <param name="currentUser"></param>
        /// <returns></returns>
        public static DataTable GetSmsByCustomer(string customerKey, string currentUser)
        {
            var sqlBuilder = new StringBuilder("SELECT CUSTOMER_KEY,CUSTOMER_NAME,CARD_NO,CONTENT,MOBILE,STATUS_NAME,OPERATOR,DATE_SEND,REASON_FAILURE FROM VL_SMS_SEND_LOG_VIEW WHERE");
            sqlBuilder.AppendFormat(" SHOP_CODE IN (SELECT SHOP_CODE FROM SYS_USER_SHOP WHERE USER_KEY='{0}')", currentUser);
            sqlBuilder.AppendFormat(" and CUSTOMER_KEY='{0}'", customerKey);

            return DB.HR.ExecuteDataSet(CommandType.Text, sqlBuilder.ToString()).Tables[0];
        }

    }
}
